package com.googlecode.scup.grammar;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.scup.grammar.grammarspart.Production;
import com.googlecode.scup.grammar.grammarspart.Rule;
import com.googlecode.scup.grammar.grammarspart.Symbol;

public class SimpleGrammar implements Grammar {
	protected List<Rule> rules;

	public SimpleGrammar(List<Rule> rules) {
		this.rules = rules;

		List<Symbol> bases = getBases();

		for (Rule rule : rules) {
			List<Production> productions  = rule.getProductions();
			for (int i = 0; i < productions.size(); ++i) {
				Production production = productions.get(i);
				for (int j = 0; j < production.size(); ++j) {
					for (Symbol base : bases) {
						Symbol s = production.getSymbol(j);
						if (base.equalsByName(s)) {
							s.setTerminal(false);
						}
					}
				}
			}
		}
	}

	@Override
	public List<Symbol> getBases() {
		List<Symbol> bases = new ArrayList<Symbol>();

		for (Rule rule : rules) {
			bases.add(rule.getBase());
		}

		return bases;
	}

	@Override
	public List<Production> getProductions(Symbol base) {
		for (Rule rule : rules) {
			if (rule.getBase().equals(base)) {
				return rule.getProductions();
			}
		}

		return null;
	}

	@Override
	public List<Rule> getRules() {
		return rules;
	}

	@Override
	public void addRule(Rule rule) {
		rules.add(rule);
	}

	@Override
	public void removeRule(Rule rule) {
		rules.remove(rule);
	}

	@Override
	public String toString() {
		StringBuilder sbuilder = new StringBuilder();

		for (Rule rule : rules) {
			sbuilder.append(rule.toString() + "\n");
		}

		return sbuilder.toString();
	}

	@Override
	public Rule getRule(Symbol base) {
		for (Rule rule : rules) {
			if (rule.getBase().equals(base)) {
				return rule;
			}
		}

		return null;
	}
}
